import React, { PureComponent } from 'react'
// import { Editor } from 'components'
// import { convertToRaw } from 'draft-js'
import {
  Button,
  Row,
  Col,
  Card,
  Typography,
  Icon,
  Layout,
  Spin,
  message,
} from 'antd'
// import draftToHtml from 'draftjs-to-html'
// import draftToMarkdown from 'draftjs-to-markdown'
import { withI18n, Trans } from '@lingui/react'
import { connect } from 'dva'
import { router } from 'utils'
import { Page } from 'components'
import { stringify } from 'qs'
import Projectslist from './components/Projectslist'
import NetWorks from './components/NetWorks'
// // import { Map, Marker, Circle, NavigationControl, InfoWindow } from 'react-bmap'
// import { Exception } from 'ant-design-pro'
const { Content } = Layout

// const { Paragraph, Title } = Typography

@withI18n()
@connect(({ devices, loras, loading }) => {
  // const { projects } = devices
  return { devices, loras, loading }
})
class Loras extends PureComponent {
  map = undefined
  constructor(props) {
    super(props)
    window.loras = this
  }
  state = {
    locationloading: false,
    Netcenterpoint: undefined,
    Netpoints: {},
    choosedDevice1: undefined,
    choosedDevice2: undefined,
  }
  isLining = false
  componentDidMount() {
    const { dispatch, devices } = this.props
    if (devices && devices.projects && devices.projects.length > 0) {
    } else {
      dispatch({
        type: 'devices/projects',
      })
    }
  }

  componentWillReceiveProps(nextprops) {
    const { devices, loras } = nextprops
    const { points } = loras
    const { choosedproject, projects } = devices
    let targetprojectdata = undefined
    if (choosedproject) {
      targetprojectdata = projects.find(_ => _.objectId == choosedproject)
    }

    // console.log("targetprojectdata:" + JSON.stringify(targetprojectdata))
    if (targetprojectdata && targetprojectdata.Geo) {
      let geo = targetprojectdata.Geo.split(',')
      const point = { lat: parseFloat(geo[0]), lng: parseFloat(geo[1]) }
      this.setState(
        {
          Netcenterpoint: { x: point.lat, y: point.lng },
          Netpoints: points,
        },
        () => {
          // setTimeout(() => {
          //   this.setMarks(points)
          //   this.centerAndZoom()
          // }, 10)
          this.setMarks(points)
          this.centerAndZoom(point)
        }
      )
    } else {
      this.initMap()
      // this.relocation()
    }
  }
  setMarks(points) {
    return
    const modal = window.loras
    var map = modal.initMap()
    map.clearOverlays()
    const makeSubMark = (key, item) => {
      const { G, O } = item
      let geo = G.split(',')
      var tmppoint = new BMap.Point(parseFloat(geo[1]), parseFloat(geo[0]))
      var p = new BMap.Marker(tmppoint)
      return p
    }
    const makeMainMark = (key, item) => {
      const { G, O } = item
      let geo = G.split(',')
      var tmppoint = new BMap.Point(parseFloat(geo[1]), parseFloat(geo[0]))
      var p = new BMap.Marker(tmppoint)
      p.addEventListener('onmousedown', function(e) {
        console.log('onmousedown')
      })
      p.addEventListener('click', function(e) {
        console.log('click')
        const { choosedDevice1, choosedDevice2 } = modal.state
        if (!choosedDevice1) {
          modal.setState({ choosedDevice1: item })
        } else if (!choosedDevice2) {
          modal.setState({ choosedDevice2: item })
        } else {
          alert('都满了')
        }
      })
      // choosedDevice1
      return p
    }
    for (let key in points) {
      // console.log(key)
      if (key) {
        let item = points[key]
        if (item && item.G) {
          map.addOverlay(
            key.indexOf(':E:') >= 0
              ? makeSubMark(key, item)
              : makeMainMark(key, item)
          )
        }
      }
    }
  }

  relocation = () => {
    return
    const { dispatch } = this.props
    const setstate = newstate => {
      this.setState(newstate)
    }
    setstate({ locationloading: true })

    const initMap = this.initMap
    var geolocation = new BMap.Geolocation()
    geolocation.enableSDKLocation()
    geolocation.getCurrentPosition(function(r) {
      if (this.getStatus() == BMAP_STATUS_SUCCESS) {
        var map = initMap()
        map.centerAndZoom(r.point, 15)
        map.panTo(r.point)
      } else {
      }
      setstate({ locationloading: false })
    })
  }

  choosePoint(location, map = undefined) {
    return
    const modal = window.loras
    if (!map) map = modal.initMap()
    var tmppoint = new BMap.Point(location.lng, location.lat)
    map.removeOverlay(modal.markpoint)
    modal.markpoint = new BMap.Marker(tmppoint)
    map.addOverlay(modal.markpoint)
    map.panTo(tmppoint)
    modal.setState({ locationloading: false })
  }

  centerAndZoom = value => {
    return
    const modal = window.loras
    var map = modal.initMap()
    if (value) {
      map.centerAndZoom(new BMap.Point(value.lng, value.lat), 15)
      modal.choosePoint(value, map)
    }
  }

  xArr = 0 //存放横坐标
  yArr = 0 //存放纵坐标
  endx = 0
  endy = 0
  moved = false

  initMap() {
    return

    const modal = window.loras

    var map = undefined
    const initcontrols = () => {
      var opts = { anchor: BMAP_ANCHOR_BOTTOM_RIGHT }
      map.enableScrollWheelZoom(true)
      map.addControl(new BMap.MapTypeControl())
      map.addControl(new BMap.ScaleControl(opts))
      map.addControl(new BMap.NavigationControl())

      map.addEventListener('touchstart', function(e) {
        //手指触摸屏幕的时候清空两个数组
        // message.info('blur')
        if (modal.inputref) modal.inputref.blur()
        if (modal.inputref2) modal.inputref2.blur()
        if (modal.inputref3) modal.inputref3.blur()
        modal.moved = false
        modal.xArr = e.targetTouches[0].pageX
        modal.yArr = e.targetTouches[0].pageY
        modal.endx = e.targetTouches[0].pageX
        modal.endy = e.targetTouches[0].pageY
      })

      map.addEventListener('touchmove', function(e) {
        //如果滑动了屏幕，xArr和yArr将各存入两个坐标值，即始末坐标值
        // xArr.push(e.targetTouches[0].pageX);
        // yArr.push(e.targetTouches[0].pageY);
        // message.info("touchmove")
        modal.moved = true
        modal.endx = e.targetTouches[0].pageX
        modal.endy = e.targetTouches[0].pageY
      })

      map.addEventListener('touchend', function(e) {
        // var endx = e.targetTouches[0].pageX
        // var endy = e.targetTouches[0].pageY
        var far
        var flag = true
        //计算平移距离，区分滑动事件和点击事件
        // if ((xArr> 1) && (yArr.length > 1)) {
        far =
          Math.abs(modal.xArr - modal.endx) ^
          (2 + Math.abs(modal.yArr - modal.endy)) ^
          2
        if (far > 0) {
          flag = false
        }
        // }
        if (flag) {
          // modal.choosePoint(e.point, map)
        }
      })

      map.addEventListener('click', function(e) {
        console.log('click')
        console.log(e)
        // modal.choosePoint(e.point, map)
      })

      var geolocationControl = new BMap.GeolocationControl(opts)
      geolocationControl.addEventListener('click', function(e) {
        console.log(e)
      })
      geolocationControl.addEventListener('locationSuccess', function(e) {
        modal.centerAndZoom(e.target.xD)
      })
      geolocationControl.addEventListener('locationError', function(e) {
        alert(e.message)
      })
      map.addControl(geolocationControl)
    }
    if (modal.map) {
      map = modal.map
    } else {
      map = new BMap.Map('loras_allmap')
      initcontrols()
    }
    modal.map = map
    return map
  }
  passThroughClick = e => {
    // const modal = window.loras
    // var map = modal.initMap()
    // var event = new Event('onclick', { bubbles: true });
    // map.dispatchEvent(event, e);
    // map.trigger("click", e)
  }
  render() {
    const { devices, loras, location, loading } = this.props
    const { query, pathname } = location
    const { locationloading, Netcenterpoint, Netpoints } = this.state
    const handleRefresh = newQuery => {
      router.push({
        pathname,
        search: stringify(
          {
            ...query,
            ...newQuery,
          },
          { arrayFormat: 'repeat' }
        ),
      })
    }

    const projectslistProps = {
      handleRefresh,
    }
    const netPoints = []
    for (var Imei in Netpoints) {
      if (Imei && Netpoints[Imei] && Netpoints[Imei].G) {
        const { G, O, N, I, Ch } = Netpoints[Imei]
        const isMain = Imei.indexOf(':E:') < 0
        const IsLined = I
        const Channel = Ch
        let geo = G.split(',')
        var parent = undefined
        if (N && Netpoints[N] && Netpoints[N].G) {
          let pgeo = Netpoints[N].G.split(',')
          parent = {
            Imei: N,
            geo: { x: pgeo[0], y: pgeo[1] },
            isMain: N.indexOf(':E:') < 0,
          }
        }
        netPoints.push({
          Imei,
          Channel,
          isMain,
          parent,
          IsLined,
          geo: { x: geo[0], y: geo[1] },
        })
      }
    }
    return (
      <Page inner>
        {/* {JSON.stringify(data)} */}
        <Content>
          <Layout style={{ padding: 0, background: '#fff' }}>
            <Projectslist {...projectslistProps} />
            <Content style={{ padding: 0 }}>
              <Spin spinning={locationloading}>
                {/* <div
                  id="loras_allmap"
                  style={{
                    width: '100%',
                    height: 0,
                  }}
                /> */}
                <NetWorks
                  {...{
                    centerpoint: Netcenterpoint,
                    points: netPoints,
                    regionPoints: Netpoints,
                  }}
                />
              </Spin>
            </Content>
          </Layout>
        </Content>
      </Page>
    )
  }
}

export default Loras
